package com.iot08.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

import javax.servlet.http.HttpServletResponse;

/**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 1/18/22 4:17 PM
 */
@Component
public class MyLocalResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取请求中的语言参数
        String language = request.getHeader("Accept-Language");
        // 获取默认的语言
        Locale locale = Locale.getDefault();

        // 如果请求的链接携带了国际化参数
        if (!StringUtils.isEmpty(language)) {
            // zh_CN 或 zh-Hans-CN 或 zh

            if(language.contains("_")){
                String[] split = language.split("_");
                // 国家，地区
                locale = new Locale(split[0], split[split.length-1]);
            }else if(language.contains("-")){
                String[] split = language.split("-");
                // 国家，地区
                locale = new Locale(split[0], split[split.length-1]);
            }else{
                // 可能是类似 zh 等
                locale = new Locale(language);
            }

        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

    //注入Bean 自定义的国际化组件就生效了
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }

}
